/*
Copyright IBM Corp. 2016 All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

		 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

//WARNING - this chaincode's ID is hard-coded in chaincode_example04 to illustrate one way of
//calling chaincode from a chaincode. If this example is modified, chaincode_example04.go has
//to be modified as well with the new ID of chaincode_example02.
//chaincode_example05 show's how chaincode ID can be passed in as a parameter instead of
//hard-coding.

// 自己写的（"溯源码"-"溯源信息"）链码
import (
	"fmt"
	
	"github.com/hyperledger/fabric/core/chaincode/shim"
	pb "github.com/hyperledger/fabric/protos/peer"
)

// WanXingChaincode example simple Chaincode implementation
// 先定义这样的结构体，然后下面函数定义func后面跟(t *WanXingChaincode)的函数都是这个结构体的方法
// (t *WanXingChaincode)相当于this
type WanXingChaincode struct {
}

func (t *WanXingChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
	fmt.Println("ex02 Init")
	// 接口 ChaincodeStubInterface 的一个方法：GetFunctionAndParameters() (string, []string)
	// GetFunctionAndParameters 返回第一个参数作为函数名，其余参数作为字符串数组中的参数。
	// 如果客户端传递要用作字符串的参数，则只使用 GetFunctionAndParameters。
	_, args := stub.GetFunctionAndParameters()
	var TranCode string    // Entities
	var Information string // Asset holdings
	var err error

	// 传来的字符串包括上传所需的所有信息，这里是TranCode和Information
	if len(args) != 2 {
		return shim.Error("Incorrect number of arguments. Expecting 2 ..")
	}

	// Initialize the chaincode
	TranCode = args[0]
	Information  = args[1]
	if err != nil {
		return shim.Error("Expecting integer value for asset holding")
	}
	fmt.Printf("TranCode = %s, Information = %s\n", TranCode, Information)

	// Write the state to the ledger
	err = stub.PutState(TranCode, []byte(Information))
	if err != nil {
		return shim.Error(err.Error())
	}

	if transientMap, err := stub.GetTransient(); err == nil {
		if transientData, ok := transientMap["result"]; ok {
			return shim.Success(transientData)
		}
	}

	return shim.Success(nil)
}

// 这是一个普遍使用的 invoke 方法
// 判断要执行的操作，然后分别调用不同的函数
func (t *WanXingChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
	fmt.Println("ex02 Invoke")
	function, args := stub.GetFunctionAndParameters()
	if function == "invoke" {
		// Make payment of X units from A to B
		return t.invoke(stub, args)
	} else if function == "delete" {
		// Deletes an entity from its state
		return t.delete(stub, args)
	} else if function == "query" {
		// the old "Query" is now implemtned in invoke
		return t.query(stub, args)
	}

	return shim.Error("Invalid invoke function name. Expecting \"invoke\" \"delete\" \"query\"")
}

// 这是一个针对特殊用途的 invoke 方法，普遍的 invoke 方法调用这个方法
func (t *WanXingChaincode) invoke(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	var TranCode string    // Entities
	var Information string // Asset holdings
	var err error

	if len(args) != 2 {
		return shim.Error("Incorrect number of arguments. Expecting 2")
	}

	TranCode = args[0]
	Information = args[1]

	// Get the state from the ledger
	// TODO: will be nice to have a GetAllState call to ledger
	fmt.Printf("TranCode = %s, Information = %s\n", TranCode, Information)

	// Write the state back to the ledger
	err = stub.PutState(TranCode, []byte(Information))
	if err != nil {
		return shim.Error(err.Error())
	}

	if transientMap, err := stub.GetTransient(); err == nil {
		if transientData, ok := transientMap["event"]; ok {
			stub.SetEvent("event", transientData)
		}
		if transientData, ok := transientMap["result"]; ok {
			return shim.Success(transientData)
		}
	}

	return shim.Success(nil)
}

// Deletes an entity from state
func (t *WanXingChaincode) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	if len(args) != 1 {
		return shim.Error("Incorrect number of arguments. Expecting 1")
	}

	TranCode := args[0]

	// Delete the key from the state in ledger
	err := stub.DelState(TranCode)
	if err != nil {
		return shim.Error("Failed to delete state")
	}

	return shim.Success(nil)
}

// query callback representing the query of a chaincode
func (t *WanXingChaincode) query(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	var TranCode string // Entities
	var err error

	if len(args) != 1 {
		return shim.Error("Incorrect number of arguments. Expecting name of the person to query")
	}

	TranCode = args[0]

	// Get the state from the ledger
	Information, err := stub.GetState(TranCode)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + TranCode + "\"}"
		return shim.Error(jsonResp)
	}

	if Information == nil {
		jsonResp := "{\"Error\":\"Nil amount for " + TranCode + "\"}"
		return shim.Error(jsonResp)
	}

	jsonResp := "{\"Name\":\"" + TranCode + "\",\"Amount\":\"" + string(Information) + "\"}"
	fmt.Printf("Query Response:%s\n", jsonResp)
	return shim.Success(Information)
}

func main() {
	err := shim.Start(new(WanXingChaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}
